import { dataSource } from "../../db/typeorm";
import { validatorData } from "../../db/utils";
import { Article, ArticleFile } from "../../entity/article";
import { formatPage, formatPageFileterData } from "../../utils/pages";
import { ArticleRoleQuery } from "./type";

// 根据分类ID、角色获取文章
export async function getArticlesByRole(
  params: ArticleRoleQuery,
  user_id: number,
) {
  const { pageIndex, pageSize } = formatPage(params);
  const queryData = formatPageFileterData(params, ["category_id", "title"]);

  let querySql = dataSource.getRepository(Article).createQueryBuilder();

  // 模糊查询
  for (const key in queryData) {
    if (Object.prototype.hasOwnProperty.call(queryData, key)) {
      if (["title"].includes(key)) {
        querySql = querySql.andWhere(`${key} LIKE :${key}`, {
          [`${key}`]: `%${queryData[key]}%`,
        });
      } else {
        querySql = querySql.andWhere(`${key} = :${key}`, {
          [`${key}`]: queryData[key],
        });
      }
    }
  }

  querySql = querySql
    .orderBy("create_time", "DESC")
    .take(pageSize)
    .skip((pageIndex - 1) * pageSize);

  const records = await querySql.getMany(); // 获取查询结果
  const total = await querySql.getCount(); // 获取符合条件的数据总数

  return { total, records };
}

// 添加文章
export async function articleCreate(
  body: Article & { files: string },
  user_id: number,
) {
  await validatorData(body, Article);
  const insertData = formatPageFileterData(body, [
    "article_id",
    "title",
    "content",
    "article_thumb",
    "category_id",
  ]);

  const files = body.files as string; // 附件
  insertData.create_user = user_id;

  await dataSource.transaction(async (transactionalEntityManager) => {
    const result = await transactionalEntityManager
      .getRepository(Article)
      .insert(insertData);
    // 更新中间表
    if (files) {
      let file_ids = files.split(",");
      let insertDatas = file_ids.map((item) => ({
        file_id: item,
        article_id: result.raw.insertId,
      }));
      await dataSource.getRepository(ArticleFile).insert(insertDatas);
    }
  });
}

// 修改文章
export async function articleUpdate(
  body: Article & { files: string },
  user_id: number,
) {
  await validatorData(body, Article);
  const insertData = formatPageFileterData(body, [
    "article_id",
    "title",
    "content",
    "article_thumb",
    "category_id",
  ]);

  const files = body.files as string; // 附件
  insertData.create_user = user_id;

  await dataSource.transaction(async (transactionalEntityManager) => {
    await transactionalEntityManager
      .createQueryBuilder()
      .update(Article)
      .set(insertData)
      .where("article_id = :id", { id: insertData.article_id })
      .execute();
    // 更新中间表
    if (files) {
      let file_ids = files.split(",");
      let insertDatas = file_ids.map((item) => ({
        file_id: item,
        article_id: insertData.article_id,
      }));
      await transactionalEntityManager
        .getRepository(ArticleFile)
        .delete(insertData.article_id as number);
      await transactionalEntityManager
        .getRepository(ArticleFile)
        .insert(insertDatas);
    }
  });
}

// 根据ids [] 删除文章
export async function articleDelByUserIds(ids: string[]) {
  await dataSource.transaction(async (transactionalEntityManager) => {
    await transactionalEntityManager.getRepository(Article).delete(ids);
    await transactionalEntityManager.getRepository(ArticleFile).delete(ids);
  });
}
